package com.personalink.reasoning.controller;

import com.personalink.common.dto.ApiResponse;
import com.personalink.common.dto.ChatRequest;
import com.personalink.common.dto.ChatResponse;
import com.personalink.reasoning.service.PersonaReasoningService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * 核心推理引擎控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/reasoning")
@RequiredArgsConstructor
@Validated
public class ReasoningController {
    
    private final PersonaReasoningService reasoningService;
    
    /**
     * 处理聊天请求
     */
    @PostMapping("/chat")
    public Mono<ApiResponse<ChatResponse>> processChat(
            @Valid @RequestBody ChatRequest request) {
        
        log.info("处理聊天请求，用户ID: {}, 会话ID: {}, 输入类型: {}", 
                request.getUserId(), request.getSessionId(), request.getInputType());
        
        return reasoningService.processChat(request)
                .map(ApiResponse::success)
                .doOnSuccess(response -> log.debug("聊天处理完成，响应ID: {}", 
                        response.getData().getResponseId()))
                .doOnError(error -> log.error("聊天处理失败", error));
    }
    
    /**
     * 流式聊天处理
     */
    @PostMapping("/chat/stream")
    public Flux<ChatResponse> processChatStream(
            @Valid @RequestBody ChatRequest request) {
        
        log.info("处理流式聊天请求，用户ID: {}, 会话ID: {}", 
                request.getUserId(), request.getSessionId());
        
        return reasoningService.processChatStream(request)
                .doOnNext(response -> log.debug("流式响应: {}", response.getResponseId()))
                .doOnError(error -> log.error("流式聊天处理失败", error));
    }
    
    /**
     * 获取当前用户的人格状态
     */
    @GetMapping("/persona/status/{userId}")
    public Mono<ApiResponse<Object>> getPersonaStatus(
            @PathVariable @NotBlank String userId) {
        
        log.debug("获取用户人格状态，用户ID: {}", userId);
        
        return reasoningService.getPersonaStatus(userId)
                .map(ApiResponse::success);
    }
    
    /**
     * 获取推理引擎统计信息
     */
    @GetMapping("/stats")
    public Mono<ApiResponse<Object>> getReasoningStats() {
        return reasoningService.getReasoningStats()
                .map(ApiResponse::success);
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public Mono<ApiResponse<String>> health() {
        return Mono.just(ApiResponse.success("推理引擎运行正常"));
    }
}